package com.doform.android.xianggucheng.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.signature.StringSignature;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.CategoryQueryBean;
import com.doform.android.xianggucheng.bean.IPickerAddressBean;
import com.doform.android.xianggucheng.bean.ImageBean;
import com.doform.android.xianggucheng.bean.VendorBean;
import com.doform.android.xianggucheng.bean.VendorDetailBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqImage;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryCategory;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryVendorBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateVendor;
import com.doform.android.xianggucheng.popwindow.PopCategory;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.BitMapUtil;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.GetJsonDataUtil;
import com.doform.android.xianggucheng.utils.KeyBoardUtils;
import com.doform.android.xianggucheng.utils.RexUtils;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.utils.thread.ThreadUtils;
import com.doform.android.xianggucheng.widget.DIYScrollView;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.google.gson.Gson;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

import static com.doform.android.xianggucheng.R.id.iv;

/**
 * Created by Administrator on 2017/5/12.
 */

public class UpdateVendorActivity extends BaseTitleActivity {


    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.et_name)
    EditText etName;

    @BindView(R.id.et_person)
    EditText etPerson;

    @BindView(R.id.et_phone)
    EditText etPhone;

    @BindView(R.id.et_addr)
    EditText etDetailAddress;

    @BindView(R.id.tv_address)
    TextView mAddress;

    @BindView(R.id.tv_category)
    TextView tv_category;

    @BindView(R.id.scrollView)
    DIYScrollView mScrollView;
    /**
     * select Picture
     */

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private String mCityId;
    private String mZoneId;
    private String mCategoryId;
    private String mCategoryName;
    private String mProvinceName;
    private String mProvinceId;
    private String mCityName;
    private String mZoneName;
    private PopCategory mPopupWindow2;
    private RecyclerView mCategoryRecyclerView;
    private VendorBean.ListBean bean;
    private List<CategoryQueryBean> mCategoryDatas = new ArrayList<>();
    private TextView tvTitle;
    private ArrayList<String> mPhotos = new ArrayList<>();
    private CommonAdapter<String> mCommonAdapter;
    private String imgId;
    private String imgFile;
    private boolean isSelectedPhotos = true;
    private View Buttonbtn_pop_submit;
    private Button btn_pop_submit;
    private Button btn_pop_cancle;

    @Override
    protected int layoutResId() {
        return R.layout.activity_new_and_update_vendor;
    }


    @Override
    protected void init() {

        if (mPopupWindow2 == null) {
            mPopupWindow2 = new PopCategory(this, R.layout.pop_category_check);
        }

        VendorBean.ListBean bean = (VendorBean.ListBean) getIntent().getExtras().getSerializable(Constans.EXTRA_UPDATE_VENDOR);
        this.bean = bean;
    }

    @Override
    protected void initView() {

        btn_pop_cancle = mPopupWindow2.getView(R.id.btn_cancel);
        btn_pop_submit = mPopupWindow2.getView(R.id.btn_submit);

        mCategoryRecyclerView = mPopupWindow2.getView(R.id.recyclerView);
        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCategoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mCategoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void initData() {
        getCategoryData();
        initDateData();
        getDataForService();
    }


    @Override
    protected void initListener() {
        super.initListener();

        mCommonAdapter = new CommonAdapter<String>(this, R.layout.item_photos, mPhotos) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, String s, final int position) {
                ImageView imageView = holder.getView(iv);
                CardView cardView = holder.getView(R.id.card_view);

                String reg = "[a-zA-z]+://[^\\s]*";
                Pattern pattern = Pattern.compile(reg);
                Matcher matcher = pattern.matcher(s);
                boolean b = matcher.matches();

                if (b) {
                    Glide.with(UpdateVendorActivity.this)
                            .load(s)
                            .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .into(imageView);
                } else {
                    Glide.with(UpdateVendorActivity.this)
                            .load(Uri.fromFile(new File(s)))
                            .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                            .into(imageView);

                    cardView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new AlertDialog.Builder(UpdateVendorActivity.this)
                                    .setTitle("删除对话框")
                                    .setMessage("确认不上传该图片？")
                                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    mPhotos.remove(position);
                                                    notifyDataSetChanged();
                                                    dialog.dismiss();
                                                }
                                            }
                                    )
                                    .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            }
                                    )
                                    .create().show();
                        }
                    });
                }
                imageView.setImageURI(Uri.fromFile(new File(s)));
            }
        };
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    //    显示数据
    private void showData(VendorDetailBean bean) {

        mCategoryId = bean.getClsids();
        mCategoryName = bean.getClsnames();

        mProvinceId = bean.getArea1();
        mProvinceName = bean.getA1name();
        mCityId = bean.getArea1();
        mCityName = bean.getA2name();
        mZoneId = bean.getArea3();
        mZoneName = bean.getA3name();

        etName.setText(bean.getName());
        etPerson.setText(bean.getLnkname());
        etPhone.setText(bean.getMobile());
        etDetailAddress.setText(bean.getAddr());

        etDetailAddress.requestFocus();
        etPhone.requestFocus();
        etPerson.requestFocus();
        etName.requestFocus();


        tv_category.setText(mCategoryName);

        if (!("".equals(mProvinceName) && TextUtils.isEmpty(mProvinceName))) {
            mAddress.setText(mProvinceName + "-" + mCityName + "-" + mZoneName);
        } else {
            mAddress.setText("未填写");
        }

        imgId = bean.getFapostcard();
        imgFile = bean.getFapostcard_imgs();

        if (imgFile != null) {
            mPhotos.clear();
            String[] sourceStrArray = imgFile.split(",");
            for (int i = 0; i < sourceStrArray.length; i++) {
                mPhotos.add(sourceStrArray[i]);
                mCommonAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("修改供应商");
    }

    private void showCategoryPop(final List<CategoryQueryBean> datas) {

        final CommonAdapter mCategoryItemCateAdapter = new CommonAdapter<CategoryQueryBean>(this, R.layout.pop_selete_category_item, datas) {
            @Override
            protected void convert(ViewHolder holder, final CategoryQueryBean categoryQueryBean, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                final CheckBox checkBox = holder.getView(R.id.checkbox);

                tv_name.setText(categoryQueryBean.getName());

                String[] strName = mCategoryName.split(",");

                for (int s = 0; s < strName.length; s++) {
                    if (strName[s].equals(categoryQueryBean.getName())) {
                        checkBox.setChecked(true);
                        categoryQueryBean.setSelete(true);
                    }

                }


                if (categoryQueryBean.isSelete()) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }


                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (categoryQueryBean.isSelete()) {
                            checkBox.setChecked(false);
                            categoryQueryBean.setSelete(false);
                        } else {
                            checkBox.setChecked(true);
                            categoryQueryBean.setSelete(true);
                        }
                    }
                });
            }
        };

        mCategoryRecyclerView.setAdapter(mCategoryItemCateAdapter);

        btn_pop_cancle.setOnClickListener(new View.OnClickListener() {//点击取消操作
            @Override
            public void onClick(View v) {
                mPopupWindow2.dismiss();
            }
        });

        btn_pop_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCategoryId = "";
                mCategoryName = "";

                Observable
                        .just(datas)
                        .map(new Function<List<CategoryQueryBean>, List<CategoryQueryBean>>() {
                                 @Override
                                 public List<CategoryQueryBean> apply(@NonNull List<CategoryQueryBean> categoryQueryBeen) throws Exception {
                                     return parseCategory1(categoryQueryBeen);
                                 }
                             }
                        ).map(new Function<List<CategoryQueryBean>, String>() {
                                  @Override
                                  public String apply(@NonNull List<CategoryQueryBean> categoryQueryBeen) throws Exception {
                                      return parseCategory2(categoryQueryBeen);
                                  }
                              }
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ErrorHandleSubscriber<String>() {
                                       @Override
                                       public void onNext(@NonNull String s) {
                                           tv_category.setText(s);
                                       }
                                   }
                        );


                mPopupWindow2.dismiss();

                tv_category.setText(mCategoryName);
            }
        });


        mPopupWindow2.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }


    private String parseCategory2(List<CategoryQueryBean> categoryQueryBeen) {

        String strId = "";
        String strName = "";

        for (int i = 0; i < categoryQueryBeen.size(); i++) {

            CategoryQueryBean bean = categoryQueryBeen.get(i);

            if (i == categoryQueryBeen.size() - 1) {
                strId = strId + bean.getId();
                strName = strName + bean.getName();
            } else {
                strId = strId + bean.getId() + ",";
                strName = strName + bean.getName() + ",";
            }
        }

        mCategoryId = strId;
        mCategoryName = strName;
        return mCategoryName;
    }

    private List<CategoryQueryBean> parseCategory1(List<CategoryQueryBean> categoryQueryBeen) {

        List<CategoryQueryBean> data = new ArrayList<>();
        data.clear();

        for (int i = 0; i < categoryQueryBeen.size(); i++) {
            CategoryQueryBean bean = categoryQueryBeen.get(i);
            if (bean.isSelete()) {
                data.add(bean);
            }
        }
        return data;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                mPhotos.clear();
                ArrayList<String> tempList = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (tempList.size() == 0) {
                    isSelectedPhotos = true;
                } else {
                    isSelectedPhotos = false;
                    mPhotos.addAll(tempList);
                    mCommonAdapter.notifyDataSetChanged();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void beforeSubmit() {

        String mName = etName.getText().toString().trim();
        String mPerson = etPerson.getText().toString().trim();
        String mPhone = etPhone.getText().toString().trim();
        String mDetailAddres = etDetailAddress.getText().toString().trim();

        if (TextUtils.isEmpty(mName)) {
            TsUtils.showToast("请输入商品名称");
            return;
        } else if (TextUtils.isEmpty(mPerson)) {
            TsUtils.showToast("请输入联系人名称");
            return;
        } else if (TextUtils.isEmpty(mPhone) && RexUtils.isMobileNO(mPhone)) {
            TsUtils.showToast("联系人电话格式不正确");
            return;
        } else if (TextUtils.isEmpty(mDetailAddres)) {
            TsUtils.showToast("请填写详细地址");
            return;
        } else if (TextUtils.isEmpty(mCategoryId) || TextUtils.isEmpty(mCategoryName)) {
            TsUtils.showToast("请选择分类");
            return;
        } else if (TextUtils.isEmpty(mZoneName)) {
            mProvinceId = "";
            mProvinceName = "";
            mCityId = "";
            mCityName = "";
            mZoneId = "";
            mZoneName = "";
        }

        if (isSelectedPhotos) {
            postDataToService(mName, mPerson, mPhone, mDetailAddres, mCategoryId, mCategoryName,
                    mProvinceId, mProvinceName, mCityId, mCityName, mZoneId, mZoneName, imgId, imgFile)
            .subscribe(new SubmitResultSubscriber2());
        } else {
            postBase64Bitmap(mName, mPerson, mPhone, mDetailAddres);
        }


    }

    private void postBase64Bitmap(final String mName, final String mPerson, final String mPhone, final String mDetailAddress) {

        Observable.just(mPhotos)
                .subscribeOn(Schedulers.io())
                .map(new Function<ArrayList<String>, String[]>() {
                         @Override
                         public String[] apply(@NonNull ArrayList<String> strings) throws Exception {
                             String imgType = "";
                             String[] strArray = new String[strings.size()];
                             for (int i = 0; i < strings.size(); i++) {
                                 if (strings.get(i).endsWith(".jpg")) {
                                     imgType = "jpg";
                                 } else if (strings.get(i).endsWith(".png")) {
                                     imgType = "png";
                                 } else if (strings.get(i).endsWith(".gif")) {
                                     imgType = "gif";
                                 } else {
                                     TsUtils.showToast("请选择png/jpg/gif格式的图片");
                                 }
                                 strArray[i] = BitMapUtil.imgCompress(strings.get(i), 480, 800, 100, imgType);
                             }
                             return strArray;
                         }
                     }
                )
                .map(new Function<String[], String>() {
                         @Override
                         public String apply(@NonNull String[] strings) throws Exception {
                             return JSON.toJSONString(strings);
                         }
                     }
                )
                .flatMap(new Function<String, ObservableSource<ArrayList<ImageBean>>>() {
                             @Override
                             public ObservableSource<ArrayList<ImageBean>> apply(@NonNull String json) throws Exception {
                                 return HttpManager.instance()
                                         .postImg(new ReqImage(json));
                             }
                         }
                )
                .flatMap(new Function<ArrayList<ImageBean>, ObservableSource<String>>() {
                             @Override
                             public ObservableSource<String> apply(@NonNull ArrayList<ImageBean> data) throws Exception {
                                 String imgId = "";
                                 String imgFilesName = "";
                                 for (int i = 0; i < data.size(); i++) {
                                     if (i == data.size() - 1) {
                                         imgId = imgId + data.get(i).getId();
                                         imgFilesName = imgFilesName + data.get(i).getUrl();
                                     } else {
                                         imgId = imgId + data.get(i).getId() + ",";
                                         imgFilesName = imgFilesName + data.get(i).getUrl() + ",";
                                     }
                                 }
                                 return postDataToService(mName, mPerson, mPhone, mCategoryId, mCategoryName, mDetailAddress,
                                         mProvinceName, mProvinceId, mCityName, mCityId, mZoneName, mZoneId, imgId, imgFilesName);
                             }
                         }
                )
                .compose(new DialogTransformer<String>(mProgressBar))
                .subscribe(new SubmitResultSubscriber2());
    }

    //    更新数据
    private Observable<String> postDataToService(String mName, String mPerson, String mPhone, String mDetailAddres, String mCategoryId, String mCategoryName,
                                                 String mProvinceId, String mProvinceName, String mCityId, String mCityName,
                                                 String mZoneId, String mZoneName, String img, String imgFile) {
        return HttpManager.instance()
                .updateVendor(new ReqUpdateVendor(mName, mPerson, mPhone, mDetailAddres, mCategoryId, mCategoryName, mProvinceId,
                        mProvinceName, mCityId, mCityName, mZoneId, mZoneName, bean.getId(), bean.getGuid(), img, imgFile));
    }

    //供应商详情
    private void getDataForService() {
        HttpManager.instance()
                .getVendorDetail(new ReqQueryVendorBean(bean.getId(), bean.getGuid()))
                .subscribe(new ErrorHandleSubscriber<ArrayList<VendorDetailBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<VendorDetailBean> vendorDetailBean) { // debug
                        showData(vendorDetailBean.get(0));
                    }
                });
    }

    private void showAddress() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvinceName = options1Items.get(options1).getPickerViewText();
                mProvinceId = String.valueOf(options1Items.get(options1).getId());

                mCityName = options2Items.get(options1).get(options2).getPickerViewText();
                mCityId = String.valueOf(options2Items.get(options1).get(options2).getCode());

                mZoneName = options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                mZoneId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getCode());

                mAddress.setText(options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2).getPickerViewText() + "-" +
                        options3Items.get(options1).get(options2).get(options3).getPickerViewText());

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private ArrayList<IPickerAddressBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<IPickerAddressBean.CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>>> options3Items = new ArrayList<>();

    private void initDateData() {

        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {


                /**
                 * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
                 * 关键逻辑在于循环体
                 *
                 * */
                String JsonData = new GetJsonDataUtil().getJson(UpdateVendorActivity.this, "province.json");//获取assets目录下的json文件数据
                ArrayList<IPickerAddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

                /**
                 * 添加省份数据
                 * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
                 * PickerView会通过getPickerViewText方法获取字符串显示出来。
                 */
                options1Items = jsonBean;

                for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                    ArrayList<IPickerAddressBean.CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
                    ArrayList<ArrayList<IPickerAddressBean.CityBean.ZoneBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

                    for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                        IPickerAddressBean.CityBean CityName = jsonBean.get(i).getCity().get(c);
                        CityList.add(CityName);//添加城市

                        ArrayList<IPickerAddressBean.CityBean.ZoneBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                        //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                        if (jsonBean.get(i).getCity().get(c).getZone() == null
                                || jsonBean.get(i).getCity().get(c).getZone().size() == 0) {
                            City_AreaList.add(new IPickerAddressBean.CityBean.ZoneBean());
                        } else {

                            for (int d = 0; d < jsonBean.get(i).getCity().get(c).getZone().size(); d++) {//该城市对应地区所有数据
                                IPickerAddressBean.CityBean.ZoneBean AreaName = jsonBean.get(i).getCity().get(c).getZone().get(d);

                                City_AreaList.add(AreaName);//添加该城市所有地区数据
                            }
                        }
                        Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                    }
                    /**
                     * 添加城市数据
                     */
                    options2Items.add(CityList);
                    /**
                     * 添加地区数据
                     */
                    options3Items.add(Province_AreaList);

                }
            }
        });
    }

    public ArrayList<IPickerAddressBean> parseData(String result) {//Gson 解析
        ArrayList<IPickerAddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                IPickerAddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), IPickerAddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


    private void getCategoryData() {

        HttpManager.instance()
                .getCategoryQuery2(new ReqQueryCategory())
                .map(new Function<ArrayList<CategoryQueryBean>, List<CategoryQueryBean>>() {
                         @Override
                         public List<CategoryQueryBean> apply(@NonNull ArrayList<CategoryQueryBean> categoryQueryBeen) throws Exception {
                             return parseCategory(categoryQueryBeen);
                         }
                     }
                ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<List<CategoryQueryBean>>() {
                               @Override
                               public void onNext(@NonNull List<CategoryQueryBean> categoryQueryBeen) {
                                   mCategoryDatas.addAll(categoryQueryBeen);
                               }
                           }
                );
    }

    private List<CategoryQueryBean> parseCategory(ArrayList<CategoryQueryBean> categoryQueryBeen) {
        List<CategoryQueryBean> data = new ArrayList<>();

        for (int i = 0; i < categoryQueryBeen.size(); i++) {
            CategoryQueryBean bean = categoryQueryBeen.get(i);
            if (bean.getFid().equals("0")) {
                data.add(bean);//为一级类
            }
        }
        return data;
    }

    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(2)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(true)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @OnClick({R.id.tv_address, R.id.btn_submit, R.id.tv_category, R.id.btn_select_pic})
    public void click(View v) {
        KeyBoardUtils.closeKeybord(etName, this);
        switch (v.getId()) {
            case R.id.btn_select_pic:
                pickPhoto();
                break;
            case R.id.tv_address:
                showAddress();
                break;
            case R.id.btn_submit:
                beforeSubmit();
                break;
            case R.id.tv_category:
                if (mCategoryDatas.size() == 0) {
                    TsUtils.showToast("请先添加商品分类");
                    return;
                }
                showCategoryPop(mCategoryDatas);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        KeyBoardUtils.closeKeybord(etDetailAddress, this);
    }

}
